/**
 * Created by kevin on 2017/7/3.
 */
/**
 * Created by kevin on 2017/6/21.
 */
var ueditor = require("ueditor");
var express = require('express');
var router = express.Router();
var path = require('path');
var Docs = require('../models/Docs');
var DocClassifies = require('../models/DocClassifies');
let ucheck = require('../utils/ucheck');



router.all('/ueditor',ueditor('./',function (req,res,next) {
    if (req.query.action === 'uploadimage') {
        console.log('start');
        var foo = req.ueditor;
        console.log(foo);

        var imgname = req.ueditor.filename;

        console.log(foo + ' ' + imgname);
        var img_url = '/data/uploads';
        res.ue_up(img_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');//IE8下载需要设置返回头尾text/html 不然json返回文件会被直接下载打开
    }
    //  客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dir_url = '/data/uploads';
        res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        // console.log('config.json')
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/ueditor/nodejs/config.json');
    }
}));

router.get('/doc',function (req,res) {
    let id = req.query.id;
    let hideNav = req.query.hide_nav;
    if (parseInt(hideNav) === 1) {
        return res.render('ueditor/detail',{title:'文档详情',docId:id,hideNav:hideNav,layout:'layout1.ejs'});
    } else {
        return res.render('ueditor/detail',{title:'文档详情',docId:id,hideNav:hideNav});
    }
});

router.get('/detail',function (req,res) {
    let id = req.query.id;
    Docs.getById(id,function (e,d) {
        if (e) {
            return res.json({
                message : e.message,
                code : -1,
                data : null
            });
        }
        return res.json({
            message : '成功',
            code : 0,
            data : d
        });
    });
});

router.get('/*',function (req,res,next) {
    ucheck.articleManager(res,function (is) {
        if (is) {
            return next();
        }
        req.flash('error', '您无权查看');
        return res.redirect('/');
    });
});

router.get('/edit',function (req,res) {
    let id = req.query.id;
    DocClassifies.getAll(function (err,classifies) {
        res.render('ueditor/edit',{title:'新增文档',classifies:classifies,docId:id});
    });
});

router.get('/list',function (req,res) {
    res.render('ueditor/list',{title:'文档列表'});
});

router.post('/list',function (req,res) {
    Docs.getAll(function (err,datas) {
        if (err) {
            return res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            return res.json({
                message : '成功',
                code : 0,
                data : datas
            });
        }
    });
});

router.post('/edit',function (req,res) {
    let name = req.body['name'];
    let weight = req.body['weight'];
    let classify = req.body['classify'];
    let content = req.body['content'];
    let id = req.body['id'];

    var errorMsg = null;
    if (!name) {
        errorMsg = '文档标题不能为空';
    }
    if (!id) {
        errorMsg = errorMsg || '系统异常，请退出后重试';
    }
    if (errorMsg) {
        return res.json({
            message : errorMsg,
            code : -1,
            data : null
        });
    }
    var doc = ({
        name : name,
        weight : weight,
        content : content,
        updateUser : res.locals.user._id,
        utime : Date.now(),
        classify: classify
    });
    Docs.edit(id,doc,function (e,d) {
        if (e) {
            return res.json({
                message : e.message,
                code : -1,
                data : null
            });
        }
        return res.json({
            message : '成功',
            code : 0,
            data : null
        });
    })
});

router.post('/del',function (req,res,next) {
    let id = req.body['id'];
    Docs.remove({'_id':id},function (err) {
        if (err) {
            res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/add',function (req,res) {
    let name = req.body['name'];
    let weight = req.body['weight'];
    let classify = req.body['classify'];
    let content = req.body['content'];

    var errorMsg = null;
    if (!name) {
        errorMsg = '文章标题不能为空';
    }
    if (errorMsg) {
        return res.json({
            message : errorMsg,
            code : -1,
            data : null
        });
    }
    var doc = ({
        name : name,
        content : content,
        weight : parseInt(weight),
        createUser : res.locals.user._id,
        updateUser : res.locals.user._id,
        classify: classify
    });
    Docs.createUniqueName(doc,function (e,d) {
        if (e) {
            return res.json({
                message : e.message,
                code : -1,
                data : null
            });
        }
        return res.json({
            message : '成功',
            code : 0,
            data : null
        });
    })
});

router.get('/classify',function (req,res) {
    res.render('ueditor/classify',{title:'文档分类列表'});
});

router.post('/classify/list',function (req,res) {
    DocClassifies.getAllexceptSystem(function (err,datas) {
        if (err) {
            return res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            return res.json({
                message : '成功',
                code : 0,
                data : datas
            });
        }
    })
});

router.post('/classify/add',function (req,res) {
    var classify = ({
        name : req.body['name'],
        recommend : req.body['recommend']
    });
    DocClassifies.createUnique(classify,function (err,data) {
        if (err) {
            return res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            return res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

router.post('/classify/edit',function (req,res) {
    var id = req.body['id'];
    if (!id) {
        return res.json({
            message : 'id不能为空',
            code : -1,
            data : null
        });
    }
    var name = req.body['name'];
    if (!name) {
        return res.json({
            message : '名称不能为空',
            code : -1,
            data : null
        });
    }
    var recommend = req.body['recommend'];
    var classify = ({
        name : name,
        recommend : recommend || false
    });
    console.log(JSON.stringify(classify));
    DocClassifies.edit(id,classify,function (err,data) {
        console.log(err + ' ' + data);
        if (err) {
            return res.json({
                message : err.message,
                code : -1,
                data : null
            });
        } else {
            return res.json({
                message : '成功',
                code : 0,
                data : null
            });
        }
    });
});

module.exports = router;
